import { NextResponse } from "next/server"
import { createOpenAI } from "@ai-sdk/openai"
import { generateObject } from "ai"
import { z } from "zod"
import { log } from "console"

// 这是一个模拟的菜品列表，实际应用中应该使用真实的AI识别
const 模拟菜品列表 = [
  "红烧肉",
  "宫保鸡丁",
  "麻婆豆腐",
  "鱼香肉丝",
  "糖醋里脊",
  "水煮鱼",
  "回锅肉",
  "东坡肉",
  "蚂蚁上树",
  "辣子鸡",
]

// 创建 OpenRouter provider 实例
const openrouter = createOpenAI({
  name: "openrouter",
  apiKey: process.env.OPENROUTER_API_KEY,
  baseURL: "https://openrouter.ai/api/v1",
})

// 定义响应的数据结构
const DishRecognitionResponseSchema = z.object({
  菜品名称: z.string(),
  置信度: z.number().min(0).max(1),
})

export async function POST(req: Request) {
  try {
    const { 图片链接 } = await req.json()
    const apiKey = process.env.OPENROUTER_API_KEY
    if (!apiKey) {
      return NextResponse.json({ error: "API 密钥未提供" }, { status: 401 })
    }

    // 使用 generateObject 识别菜品
    const { object } = await generateObject({
      model: openrouter('openai/gpt-4o-2024-11-20'), // 假设有一个菜品识别模型
      schema: DishRecognitionResponseSchema,
      prompt: `识别图片中的菜品，图片链接：${图片链接}。`,
      maxRetries: 3,
    })

    // Validate the recognition result to ensure it matches the expected schema
    try {
      DishRecognitionResponseSchema.parse(object)
    } catch (validationError) {
      console.error("响应数据格式错误:", validationError)
      return NextResponse.json({ error: "菜品识别返回的数据格式错误" }, { status: 500 })
    }

    return NextResponse.json(object)
  } catch (error) {
    console.error("菜品识别出错:", error)
    return NextResponse.json({ error: "菜品识别失败111" }, { status: 500 })
  }
}
